package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.VerificationCodeDTO;
import com.rdc.example.dao.impl.VerificationCodeDaoImpl;
import com.rdc.example.entity.VerificationCode;

import java.time.LocalDateTime;
import java.util.UUID;

public class VerificationCodeServiceImpl implements com.rdc.example.service.VerificationCodeService {

    VerificationCodeDaoImpl verificationCodeDao = new VerificationCodeDaoImpl();

    @Override
    public Result insertManagerCode(Integer userId) throws Exception {
        if (userId == null) {
            return Result.fail("userId为空", null);
        }
        String uuid= UUID.randomUUID().toString();
        VerificationCode entity = new VerificationCode();
        entity.setUserId(userId);entity.setContent(uuid);
        // 获取当前时间一天之后的时间
        LocalDateTime oneDayLater = LocalDateTime.now().plusDays(1);
        entity.setEndAt(oneDayLater);
        entity.setType(0);
        boolean insert =verificationCodeDao.insert(entity);
        return insert?Result.success("创建成功",uuid)
                : Result.fail("创建失败",null);
    }

    @Override
    public Result checkAndUseCodeToManager(String code) throws Exception {
        //验证数据是否合法
        if (code == null|| code.isEmpty()) {
            return Result.fail("VerificationCode为空", null);
        }
        // 0 管理员验证码 1新用户验证码
        VerificationCode verificationCode=verificationCodeDao.getByCode(code,0);
        if (verificationCode == null||!code.equals(verificationCode.getContent())) {
            //不正确
            return Result.fail("验证码错误", null);
        }
        if (verificationCode.getEndAt() == null||verificationCode.getEndAt().isBefore(LocalDateTime.now())) {
            //过期了
            return Result.fail("验证码已过期", null);
        }
        if (verificationCode.getIsUsed()==1) {
            //用过了
            return Result.fail("验证码已使用", null);
        }
        //'使用':更新该验证码使用状态
        boolean use=verificationCodeDao.useVerificationCode(code);
        return use ? Result.success("验证成功",null)
                :Result.fail("验证码错误", null);
    }









    /*private VerificationCode convertToEntity(VerificationCodeDTO dto) {
        VerificationCode entity = new VerificationCode();
        entity.setId(dto.getId());
        entity.setUserId(dto.getUserId());
        entity.setType(dto.getType());
        entity.setIsUsed(dto.getIsUsed());
        entity.setContent(dto.getContent());
        entity.setCreatedAt(dto.getCreatedAt());
        entity.setEndAt(dto.getEndAt());
        return entity;
    }*/
}
